<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getDonationTypeAPI } from '@/services/home'
import type { DonationType } from '@/types/home'
import DonationList from './components/donation-list.vue'
import { putCancelOrder } from '@/services/donationDetail'
import { donationTypeStore } from '@/stores/modules/donationType'

// 页面参数类型
interface PageOptions {
  type?: string // 类型：donate(捐赠) 或 pickup(取货)
  status?: string // 可选的初始状态
}

// 当前类型：捐赠或取货
const currentType = ref('donate')

// 捐赠状态选项
const donateStatusTabs = [
  { name: '待审核', value: '0' },
  { name: '待入库', value: '2' },
  { name: '已完成', value: '7' },
  { name: '已取消', value: '1' },
]

// 取货状态选项
const pickupStatusTabs = [
  { name: '全部', value: '' },
  { name: '待取货', value: '6' },
  { name: '已完成', value: '4' },
  { name: '收藏', value: 'favorite' },
]

// 当前状态索引
const currentStatusIndex = ref(0)

// 当前活跃的状态数组
const statusTabs = computed(() => {
  return currentType.value === 'donate' ? donateStatusTabs : pickupStatusTabs
})

// 捐赠物种类列表
let donationTypes = donationTypeStore().donationTypes

// 加载状态
const loading = ref(false)

// 状态栏高度
const statusBarHeight = ref(20)
// 导航栏高度
const navBarHeight = 44

// 获取捐赠物种类列表 - 只在页面加载时获取一次
const fetchDonationTypes = async () => {
  if (donationTypes.length > 0) return

  try {
    const res = await getDonationTypeAPI()
    if (res.code === 200 && res.rows) {
      donationTypes = res.rows
    }
  } catch (error) {
    console.error('获取捐赠物种类失败:', error)
  }
}

// swiper设置
const swiperHeight = ref(0)
const setSwiperHeight = () => {
  uni.getSystemInfo({
    success: (res) => {
      statusBarHeight.value = res.statusBarHeight || 20
      // 计算swiper高度 (屏幕高度 - 状态栏高度 - 导航栏高度 - 状态分类高度 - 其他边距)
      swiperHeight.value = res.windowHeight - statusBarHeight.value - navBarHeight - 80
    },
  })
}

// 列表组件引用
const listRefs = ref<any[]>([])

// 状态分类swiper切换
const handleStatusSwiperChange = (e: any) => {
  currentStatusIndex.value = e.detail.current
}

// 状态分类标签点击
const handleStatusTabClick = (index: number) => {
  // 如果点击当前已选中的标签，不做任何处理
  if (currentStatusIndex.value === index) return

  currentStatusIndex.value = index
}

// 处理下拉刷新
const onRefresh = async () => {
  // 获取当前激活的列表组件
  const currentList = getCurrentListComponent()
  if (currentList) {
    await currentList.refreshData()
  }
}

// 加载更多数据
const loadMoreData = () => {
  // 获取当前激活的列表组件
  const currentList = getCurrentListComponent()
  if (currentList) {
    currentList.loadMoreData()
  }
}

// 获取当前激活的列表组件
const getCurrentListComponent = () => {
  return listRefs.value[currentStatusIndex.value]
}

// 更新列表引用数组
const updateListRefs = (el: any) => {
  if (el && !listRefs.value.includes(el)) {
    listRefs.value.push(el)
  }
}

// 清空列表引用
const resetListRefs = () => {
  listRefs.value = []
}

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

// 处理取消订单
const handleCancelOrder = async (orderId: number, cancelReason: string) => {
  // 这里调用实际的取消订单API
  const res = await putCancelOrder({ id: orderId, cancelReason: cancelReason })
}

// 页面加载
onLoad((options?: PageOptions) => {
  console.log('options:', options)

  // 设置当前类型：捐赠或取货
  if (options?.type && (options.type === 'donate' || options.type === 'pickup')) {
    currentType.value = options.type
  }

  // 设置初始状态索引
  if (options?.status) {
    const tabs = currentType.value === 'donate' ? donateStatusTabs : pickupStatusTabs
    const statusIndex = tabs.findIndex((item) => item.value === options.status)
    if (statusIndex !== -1) {
      currentStatusIndex.value = statusIndex
    }
  }

  // 设置swiper高度
  setSwiperHeight()

  // 获取捐赠物种类列表
  fetchDonationTypes()
})

onMounted(() => {
  // 设置swiper高度
  setSwiperHeight()

  // 获取捐赠物种类列表
  fetchDonationTypes()

  // 添加全局事件监听器，用于监听从详情页发来的刷新请求
  uni.$on('refreshOrderList', handleRefreshFromDetail)
})

// 组件卸载时移除事件监听器，防止内存泄漏
onUnmounted(() => {
  uni.$off('refreshOrderList', handleRefreshFromDetail)
})

// 处理从详情页发来的刷新请求
function handleRefreshFromDetail() {
  console.log('收到刷新请求，正在刷新列表...')
  onRefresh()
}
</script>

<template>
  <view class="my-orders">
    <!-- 自定义导航栏 -->
    <view class="custom-nav" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-content">
        <view class="nav-left" @tap="handleBack">
          <view class="back-btn">
            <view class="back-icon">
              <text class="iconfont icon-arrow-left"></text>
            </view>
          </view>
        </view>
        <view class="nav-title">{{ currentType === 'donate' ? '我的捐赠' : '我的取货' }}</view>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 状态分类栏 -->
    <view class="status-tabs-container">
      <view class="status-tabs">
        <view
          v-for="(tab, index) in statusTabs"
          :key="tab.value"
          class="status-item"
          :class="{ active: currentStatusIndex === index }"
          @tap="handleStatusTabClick(index)"
        >
          {{ tab.name }}
        </view>
        <view
          class="status-indicator"
          :style="{
            left: `calc((100% / ${statusTabs.length}) * ${currentStatusIndex} + (100% / ${statusTabs.length} / 2) - 15rpx)`,
          }"
        ></view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 切换时重置列表引用 -->
      <view style="display: none" @hook:mounted="resetListRefs"></view>

      <swiper
        class="status-swiper"
        :current="currentStatusIndex"
        @change="handleStatusSwiperChange"
        :style="{ height: swiperHeight + 'px' }"
      >
        <swiper-item v-for="(tab, index) in statusTabs" :key="index">
          <scroll-view
            scroll-y
            class="scroll-view"
            @scrolltolower="loadMoreData"
            @refresherrefresh="onRefresh"
            refresher-enabled
            :refresher-triggered="loading"
          >
            <donation-list
              ref="updateListRefs"
              :donation-types="donationTypes"
              :type="currentType"
              :status="tab.value"
              @update:loading="loading = $event"
              @cancel-order="handleCancelOrder"
            />
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<style lang="scss">
.my-orders {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f9fa;
}

// 自定义导航栏
.custom-nav {
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .nav-content {
    display: flex;
    align-items: center;
    height: 44px;
    padding: 0 20rpx;

    .nav-left {
      width: 80rpx;
      display: flex;
      align-items: center;

      .back-btn {
        display: flex;
        align-items: center;
        justify-content: center;

        .back-icon {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          background-color: #f0f0f0;
          display: flex;
          align-items: center;
          justify-content: center;

          .iconfont {
            font-size: 32rpx;
            color: #333;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
      }
    }

    .nav-title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .nav-right {
      width: 80rpx;
    }
  }
}

// 状态分类栏容器
.status-tabs-container {
  padding: 20rpx;

  .status-tabs {
    display: flex;
    background-color: #fff;
    padding: 20rpx 0;
    position: relative;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    border-radius: 12rpx;

    .status-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #666;
      position: relative;
      padding: 10rpx 0;

      &.active {
        color: #4a69bd;
        font-weight: bold;
      }
    }

    .status-indicator {
      position: absolute;
      bottom: 10rpx;
      width: 30rpx;
      height: 6rpx;
      background-color: #4a69bd;
      border-radius: 3rpx;
      transition: left 0.3s;
    }
  }
}

// 内容区域
.content-area {
  flex: 1;
  padding: 0 20rpx;

  .status-swiper {
    height: 100%;
  }

  .scroll-view {
    height: 100%;
  }
}
</style>
